package com.elong.android.specialhouse.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.constants.JSONConstants;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.PushContent;
import com.elong.android.specialhouse.entity.TypePushMessage;
import com.elong.android.specialhouse.entity.response.GetPushMessageListResp;
import com.elong.android.specialhouse.entity.response.MessageResult;
import com.elong.android.specialhouse.notification.MyNotificationManager;
import com.elong.android.specialhouse.request.GetMessageListReq;
import com.elong.android.specialhouse.request.RemoveMessageListReq;
import com.elong.android.specialhouse.ui.SuperListView;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author kaiqi.li
 * @Description
 * @date 2015/9/21 18:04
 */
public class MessageListActivity extends BaseVolleyActivity<IResponse<?>> implements AdapterView.OnItemClickListener {

    private SuperListView lvMessage;
    private RelativeLayout rlNoMessage;
    private PowerAdapter<Object> mAdapter;
    private List<Object> list = new ArrayList<Object>();
    private int deletePositon;//记录当前删除的信息位置

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_message_list);
        setHeader(R.string.message);

        lvMessage = (SuperListView) findViewById(R.id.lv_message);

        rlNoMessage = (RelativeLayout) findViewById(R.id.rl_no_message);
//        this.list = generateTestData();
//        if(this.list == null){
//	        	rlNoMessage.setVisibility(View.VISIBLE);
//	        	lvMessage.setVisibility(View.GONE);
//        }else{
//	        	rlNoMessage.setVisibility(View.GONE);
//	        	lvMessage.setVisibility(View.VISIBLE);
//        }
//        setUpMsgList();
//        setData(true);
        setListViewOnItemLongClick();
        lvMessage.setLastPage();
        lvMessage.setOnRefreshListener(new SuperListView.OnPullDownRefreshListener() {

            @Override
            public void onRefresh() {
                setData(false);
            }
        });
    }

    /**
     * 添加listview中item长按删除的菜单
     */
    private void setListViewOnItemLongClick() {
        lvMessage.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenuInfo menuInfo) {
                menu.add(0, 0, 0, R.string.menu_delete_message);
            }
        });

    }

    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        deletePositon = info.position - 1;
        Object msg = list.get(info.position - 1);
        switch (item.getItemId()) {
            case 0:
                // 添加操作 
                if (msg instanceof MessageResult) {
                    MessageResult msgEntry = (MessageResult) msg;
                    if (msgEntry.SenterId == Long.valueOf(Account.getInstance().getUserId())) {
                        deleteMessage(msgEntry.CollectId, msgEntry.SenterId);
                    } else {
                        deleteMessage(msgEntry.SenterId, msgEntry.CollectId);
                    }
                } else if (msg instanceof TypePushMessage) {
                    //删除系统消息
                    TypePushMessage notification = (TypePushMessage) msg;
                    deleteMessage(notification.pushMessageVo.receiverId, notification.pushMessageVo.senderId);
                }
                break;
            default:
                break;
        }

        return super.onContextItemSelected(item);

    }

    @Override
    protected void onResume() {
        super.onResume();
        setData(true);
    }

    private void setUpMsgList() {
        mAdapter = new PowerAdapter<Object>(this, R.layout.item_message_list, list) {
            @Override
            protected void convert(BaseViewHolder holder, Object item) {
                if (item instanceof MessageResult) {
                    MessageResult chatMessage = (MessageResult) item;
                    if (chatMessage.SenterId == Long.valueOf(Account.getInstance().getUserId())) {
                        holder.setText(R.id.tv_msg_label, chatMessage.CollectName);
                    } else {
                        holder.setText(R.id.tv_msg_label, chatMessage.SenterName);
                    }
                    holder.setText(R.id.tv_msg_desc, chatMessage.Content);
                    Date date = DateTimeUtils.getDateFromString(chatMessage.SendTime, "yyyy-MM-dd HH:mm:ss");
                    if (date != null) {
                        holder.setText(R.id.tv_msg_time, DateTimeUtils.getDisplayTime(date));
                    }
                    if (chatMessage.SenterId == Long.valueOf(Account.getInstance().getUserId())) {
                        holder.setImageUrl(R.id.vi_msg_photo, chatMessage.CollectUrl, R.drawable.icon_default_img_for_msg);
                    } else {
                        holder.setImageUrl(R.id.vi_msg_photo, chatMessage.SenterUrl, R.drawable.icon_default_img_for_msg);
                    }
                    if (chatMessage.State != null) {
                        if (chatMessage.State == 1) {
                            holder.setVisible(R.id.vi_had_look, false);
                        } else {
                            holder.setVisible(R.id.vi_had_look, true);

                        }
                    }
                } else if (item instanceof TypePushMessage) {
                    TypePushMessage systemmsg = (TypePushMessage) item;
                    String title = null;
                    switch (systemmsg.pushMessageVo.msgType) {
                        case 0:
                            title = getResources().getString(R.string.order_notification);
                            holder.setImageResource(R.id.vi_msg_photo, R.drawable.icon_order_message);
                            break;
                        case 1:
                            holder.setImageResource(R.id.vi_msg_photo, R.drawable.icon_settlenotification);
                            title = getResources().getString(R.string.settlement_notification);
                            break;
                        case 2:
                            holder.setImageResource(R.id.vi_msg_photo, R.drawable.icon_system_notification);
                            title = getResources().getString(R.string.system_notification);
                            break;
                        default:
                            break;
                    }
                    holder.setText(R.id.tv_msg_label, title);
                    String content = systemmsg.pushMessageVo.content ;
                    PushContent pushContent = null ;
                    try {
                        pushContent = JSON.parseObject(content, PushContent.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (pushContent != null) {
                        holder.setText(R.id.tv_msg_desc, pushContent.title + "  " + pushContent.desc);
                    }
                    holder.setText(R.id.tv_msg_time, DateTimeUtils.getDisplayTime(systemmsg.pushMessageVo.sendTime));
                    if (systemmsg.isUnread) {
                        holder.setVisible(R.id.vi_had_look, true);
                    } else {
                        holder.setVisible(R.id.vi_had_look, false);
                    }
                }
            }
        };
        lvMessage.setAdapter(mAdapter);
        lvMessage.setOnItemClickListener(this);
    }

    private List<MessageResult> generateTestData() {
        List<MessageResult> list = new ArrayList<MessageResult>();
        for (int i = 0; i < 10; i++) {
            MessageResult item = new MessageResult();
            item.CollectName = "item" + i;
            list.add(item);
        }
        return list;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object item = list.get(position - 1);
        Intent intent = null;
        //title 用于点击某一条消息时同时清除通知栏的通知
        String title = "" ;
        if (item instanceof MessageResult) {
            MessageResult chatmessage = (MessageResult) item;
            intent = new Intent(MessageListActivity.this, ChatActivity.class);
            Long sendid = chatmessage.SenterId;
            String name = chatmessage.SenterName;
            title = name ;

            if (Long.valueOf(Account.getInstance().getUserId()) == chatmessage.SenterId) {
                sendid = chatmessage.CollectId;
                name = chatmessage.CollectName;
            }
            intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID, sendid);
            intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME, name);

        } else if (item instanceof TypePushMessage) {
            TypePushMessage notification = (TypePushMessage) item;
//        		Intent in = null;
            switch (notification.pushMessageVo.msgType) {
                case 0:
                    intent = new Intent(this, OrderMessageListActivity.class);
                    title = getResources().getString(R.string.order_notification);
                    break;
                case 1:
                    intent = new Intent(this, SettlingAccountsMessageListActivity.class);
                    title = getResources().getString(R.string.settlement_notification);
                    break;
                case 2:
                    intent = new Intent(this, SystemNotifitionListAcivity.class);
                    title = getResources().getString(R.string.system_notification);
                    break;
            }
        }
        MyNotificationManager.getInstanse().cancelNotification(title);
        startActivity(intent);
    }

    private void setData(boolean hasWaiting) {
        if (Account.getInstance().isLogin()) {
            GetMessageListReq param = new GetMessageListReq();
            try {
                param.userId = Long.valueOf(Account.getInstance().getUserId());
                param.tagType = 7;
                requestHttp(param, ApartmentAPI.getMessageList, StringResponse.class, hasWaiting);
            } catch (Exception e) {
                e.printStackTrace();
                rlNoMessage.setVisibility(View.VISIBLE);
                lvMessage.setVisibility(View.GONE);
            }
        } else {
            rlNoMessage.setVisibility(View.VISIBLE);
            lvMessage.setVisibility(View.GONE);
        }
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        JSONObject result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
        if (result == null) {
            return;
        }
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case getMessageList:
                this.list.clear();
                lvMessage.onRefreshComplete();
                if (result.getBoolean(JSONConstants.ATTR_ISERROR)) {
                    String message = result.getString(JSONConstants.ATTR_ERRORMESSAGE);
                    if (!TextUtils.isEmpty(message)) {
                        ToastUtils.show(this, message);
                    }
                    rlNoMessage.setVisibility(View.VISIBLE);
                    lvMessage.setVisibility(View.GONE);
                } else {
                    GetPushMessageListResp messagelist = JSON.parseObject(result.toJSONString(), GetPushMessageListResp.class);

                    if (messagelist.messageListMap != null) {
                        for (int i = 0; i < messagelist.messageListMap.size(); i++) {
                            TypePushMessage pushmessage = messagelist.messageListMap.get(i);
                            if (pushmessage.pushMessageVo != null) {
                                this.list.add(pushmessage);
                            }
                        }
                    }
                    if (messagelist.chatMessageList.MessageList != null && messagelist.chatMessageList.MessageList.size() > 0) {
                        this.list.addAll(messagelist.chatMessageList.MessageList);
                    }
                    if (this.list == null || this.list.size() == 0) {
                        rlNoMessage.setVisibility(View.VISIBLE);
                        lvMessage.setVisibility(View.GONE);
                    } else {
                        rlNoMessage.setVisibility(View.GONE);
                        lvMessage.setVisibility(View.VISIBLE);
                    }
                    setUpMsgList();
                }
                break;
            case removeMessageList:
                if (result.getBoolean(JSONConstants.ATTR_ISERROR)) {
                    String message = result.getString(JSONConstants.ATTR_ERRORMESSAGE);
                    ToastUtils.show(this, message);
                } else {
                    list.remove(deletePositon);
                    mAdapter.remove(deletePositon);
                    if (list.size() == 0) {
                        rlNoMessage.setVisibility(View.VISIBLE);
                        lvMessage.setVisibility(View.GONE);
                    }
                }
                break;
        }
//    		}else{
//    			rlNoMessage.setVisibility(View.VISIBLE);
//	        	lvMessage.setVisibility(View.GONE);
//    		}
    }

    /**
     * 删除消息
     *
     * @param senderid
     * @param collectid
     */
    private void deleteMessage(Long senderid, Long collectid) {
        RemoveMessageListReq param = new RemoveMessageListReq();
        param.SenderId = senderid;
        param.CollectId = collectid;
        requestHttp(param, ApartmentAPI.removeMessageList, StringResponse.class, true);
    }

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_MESSAGE_LIST;
    }

    @Override
    protected void onReceive(Intent intent) {
        setData(true);

    }
}